<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
      <!-- $router.go(-1) 返回上一页 -->
    </div>
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
       :immediate-check="false"
      >
        <Articleltem
          v-for="obj in searchResults"
          :key="obj.art_id"
          :objList="obj"
          :isShow="false"
          @click.native="articleClick(obj.art_id)"
        ></Articleltem>
      </van-list>
    </div>
  </div>
</template>

<script>
import { searchResultApi } from '@/api'
import Articleltem from '@/components/ArticleItem'
export default {
  name: 'SearchResult',
  data () {
    return {
      page: 1, // 页码
      searchResults: [], // 搜索结果列表
      loading: false, // 加载状态
      finished: false // 是否全部加载完成
    }
  },
  // 页面初始化 -> 请求数据
  async created () {
    this.page = 1 // 初始化页码
    const res = await searchResultApi({
      page: this.page,
      q: this.$route.params.keywords
    })
    this.searchResults = res.data.data.results
  },
  methods: {
    // 下拉 -> 请求数据
    async onLoad () {
      if (this.searchResults.length > 0) {
        this.page++
        const res = await searchResultApi({
          page: this.page,
          q: this.$route.params.keywords
        })
        console.log(res)
        if (res.data.data.results.length === 0) {
          this.finished = true
          return
        }
        this.searchResults = [...this.searchResults, ...res.data.data.results]
        this.loading = false
      }
    },

    // 文章 -> 点击 -> 跳转搜索内容页面
    articleClick (id) {
      this.$router.push({
        path: `/Articledetail?art_id=${id}`
      })
    }
  },

  components: {
    // eslint-disable-next-line vue/no-unused-components
    Articleltem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
